package com.hy.java.utility.nlp;

import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.SetUtils;

/**
 * 计算各种相似度
 */
public class SimilarityCalculator {
	/**
	 * 计算两个字符串的Jaccard相似度
	 */
	public static double jaccard_similarity(String string1, String string2) {
		double result = 0.0;
		// 两个字符串的字符集
		Set<Integer> chars_of_string1 = string1.chars().boxed().collect(Collectors.toSet());
		Set<Integer> chars_of_string2 = string2.chars().boxed().collect(Collectors.toSet());
		// 交集大小
		int intersection = SetUtils.intersection(chars_of_string1, chars_of_string2).size();
		// 并集大小
		int union = SetUtils.union(chars_of_string1, chars_of_string2).size();
		// Jaccard相似度
		if (union != 0) {
			result = ((double) intersection) / ((double) union);
		}
		return result;
	}
}
